import store from '@/store'
import axios from 'axios'
import util from '@/libs/util'
import { Message } from 'element-ui'

// 创建一个错误
function errorCreate (msg) {
  const err = new Error(msg)
  errorLog(err)
}
// 记录和显示错误
function errorLog (err) {
  // 添加到日志
  store.dispatch('admin/log/push', {
    message: '数据请求异常',
    type: 'error',
    meta: {
      error: err
    }
  })
  // 打印到控制台
  if (process.env.NODE_ENV === 'development') {
    util.log.error('>>>>>> Error >>>>>>')
  }
  if (err.message) {
    Message.error({
      message: err.message,
      type: 'error',
      customClass: 'element_message_error'
    })
  }
}
const service = axios.create({
  baseURL: '/srm-export/',
  timeout: 1200000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  }
})
// 请求拦截器
service.interceptors.request.use(
  config => {
    return config
  },
  error => {
    Promise.reject(error)
  }
)
// 响应拦截器
service.interceptors.response.use(
  response => {
    const resData = response.data
    const { status } = resData
    // 0 成功 1 失败
    if (status == 0 || !status) {
      return resData
    }
    errorCreate(resData.message)
  },
  error => {
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '请求错误'
          break
        case 401:
          error.message = '您还未登录或者登录超时'
          break
        case 403:
          error.message = '拒绝访问'
          break
        case 404:
          error.message = `请求地址出错: ${error.response.config.url}`
          break
        case 408:
          error.message = '请求超时'
          break
        case 500:
          error.message = '服务器内部错误'
          break
        case 501:
          error.message = '服务未实现'
          break
        case 502:
          error.message = '网关错误'
          break
        case 503:
          error.message = '服务不可用'
          break
        case 504:
          error.message = '网关超时'
          break
        case 505:
          error.message = 'HTTP版本不受支持'
          break
        default:
          break
      }
    }
    errorLog(error)
    return Promise.reject(error)
  }
)

export default service
